package com.netdevsdk.demo;

import com.netdevsdk.lib.NetDEVSDKLib;

/**
 * 自动登录功能类 - 完全模拟UI登录逻辑
 */
public class AutoLogin {
    
    // 默认登录参数
    private static final String DEFAULT_IP = "192.168.10.232";
    private static final String DEFAULT_PORT = "80";
    private static final String DEFAULT_USERNAME = "admin";
    private static final String DEFAULT_PASSWORD = "admin";
    
    /**
     * 完全复制UI登录逻辑
     */
    public static void autoLogin() {
        System.out.println("=== 完全复制UI登录逻辑 ===");
        
        String strUserName = DEFAULT_USERNAME;
        String strPassword = DEFAULT_PASSWORD;
        String strPort = DEFAULT_PORT;
        NetDemo.strIPAddr = DEFAULT_IP;
        
        // 参数检查（与UI相同）
        if(strUserName.isEmpty()){
            System.out.println("Enter UserName first.");
            return;
        }
        if(NetDemo.strIPAddr.isEmpty()){
            System.out.println("Enter IP first.");
            return;
        }
        if(strPort.isEmpty()){
            System.out.println("Enter Port first.");
            return;
        }
        
        NetDEVSDKLib.NETDEV_DEVICE_LOGIN_INFO_S stDevLoginInfo = new NetDEVSDKLib.NETDEV_DEVICE_LOGIN_INFO_S();
        NetDEVSDKLib.NETDEV_SELOG_INFO_S stSELogInfo = new NetDEVSDKLib.NETDEV_SELOG_INFO_S();
        
        // 关键：完全复制UI中的数组拷贝方式
        System.arraycopy(strUserName.getBytes(), 0, stDevLoginInfo.szUserName, 0, strUserName.getBytes().length);
        System.arraycopy(strPassword.getBytes(), 0, stDevLoginInfo.szPassword, 0, strPassword.getBytes().length);
        System.arraycopy(NetDemo.strIPAddr.getBytes(), 0, stDevLoginInfo.szIPAddr, 0, NetDemo.strIPAddr.getBytes().length);
        
        int getStrPort=0;
        try {
            getStrPort=Integer.parseInt(strPort);
        }catch(Exception m) {
            System.out.println("Port Conversion Exception");
            return;
        }
        
        if(getStrPort<1 || getStrPort>65535) {
            System.out.println("Port should between 1 and 65535");
            return;
        }
        stDevLoginInfo.dwPort = getStrPort;
        
        // 关键：协议设置 - 使用与UI完全相同的逻辑
        // 在UI中，当选择ONVIF时，jComboBoxLoginProtocol.getSelectedIndex() 返回的值
        stDevLoginInfo.dwLoginProto = 1; // ONVIF协议
        
        System.out.println("登录参数:");
        System.out.println("  IP: " + NetDemo.strIPAddr);
        System.out.println("  端口: " + stDevLoginInfo.dwPort);
        System.out.println("  用户名: " + strUserName);
        System.out.println("  协议: " + stDevLoginInfo.dwLoginProto);
        
        // 打印字节数组内容用于调试
        printByteArray("szUserName", stDevLoginInfo.szUserName);
        printByteArray("szPassword", stDevLoginInfo.szPassword);
        printByteArray("szIPAddr", stDevLoginInfo.szIPAddr);
        
        // 执行登录
        System.out.println("执行 NETDEV_Login_V30...");
        NetDemo.lpUserID = NetDemo.netdevsdk.NETDEV_Login_V30(stDevLoginInfo, stSELogInfo);
        
        if(null != NetDemo.lpUserID){
            System.out.println("✅ 自动登录成功!");
            System.out.println("用户ID: " + NetDemo.lpUserID);
            
            // 继续执行UI中的成功逻辑
            onLoginSuccess();
        }
        else
        {
            int errorCode = NetDemo.netdevsdk.NETDEV_GetLastError();
            System.out.println("❌ 自动登录失败! 错误代码: " + errorCode);
            if(errorCode == 11201){
                System.out.println("Login failed, Please check username and password");
            }else {
                System.out.println("Login failed, Please check device information.");
            } 
        }
    }
    
    /**
     * 打印字节数组内容
     */
    private static void printByteArray(String name, byte[] array) {
        System.out.print("  " + name + ": [");
        for (int i = 0; i < Math.min(array.length, 32); i++) {
            if (array[i] != 0) {
                System.out.print((char)array[i]);
            }
        }
        System.out.println("]");
    }
    
    /**
     * 登录成功后的处理
     */
    private static void onLoginSuccess() {
        try {
            // 获取设备基本信息（与UI相同）
            NetDEVSDKLib.NETDEV_DEVICE_BASE_INFO_S pstDeviceInfo = new NetDEVSDKLib.NETDEV_DEVICE_BASE_INFO_S();
            pstDeviceInfo.write();
            boolean bRet = NetDemo.netdevsdk.NETDEV_GetDeviceBaseInfo(NetDemo.lpUserID, pstDeviceInfo);
            if(bRet != true){
                System.out.println("NETDEV_GetDeviceBaseInfo failed:%d\n" + NetDemo.netdevsdk.NETDEV_GetLastError());
                return;
            }
            pstDeviceInfo.read();
            
            System.out.println("设备基本信息:");
            System.out.println("  设备类型: " + pstDeviceInfo.dwDeviceType);
            
        } catch (Exception e) {
            System.err.println("获取设备信息异常: " + e.getMessage());
        }
    }
    
    /**
     * 测试SDK初始化
     */
    public static void testSDKInitialization() {
        System.out.println("\n=== 测试SDK初始化 ===");
        try {
            // 检查SDK是否已加载
            if (NetDemo.netdevsdk == null) {
                System.err.println("SDK未加载!");
                return;
            }
            
            // 尝试初始化SDK
            boolean initResult = NetDemo.netdevsdk.NETDEV_Init();
            System.out.println("SDK初始化结果: " + initResult);
            
            // 设置异常回调
            com.sun.jna.Pointer lpUserData = new com.sun.jna.Memory(128);
            boolean callbackResult = NetDemo.netdevsdk.NETDEV_SetExceptionCallBack(NetDemo.cbExceptionCallBack, lpUserData);
            System.out.println("设置异常回调结果: " + callbackResult);
            
        } catch (Exception e) {
            System.err.println("SDK初始化测试异常: " + e.getMessage());
        }
    }
    
    /**
     * 测试不同的编码方式
     */
    public static void testDifferentEncodings() {
        System.out.println("\n=== 测试不同编码方式 ===");
        
        String[] encodings = {"UTF-8", "GBK", "ISO-8859-1"};
        
        for (String encoding : encodings) {
            System.out.println("\n测试编码: " + encoding);
            try {
                NetDEVSDKLib.NETDEV_DEVICE_LOGIN_INFO_S stDevLoginInfo = new NetDEVSDKLib.NETDEV_DEVICE_LOGIN_INFO_S();
                NetDEVSDKLib.NETDEV_SELOG_INFO_S stSELogInfo = new NetDEVSDKLib.NETDEV_SELOG_INFO_S();
                
                // 使用指定编码
                byte[] usernameBytes = DEFAULT_USERNAME.getBytes(encoding);
                byte[] passwordBytes = DEFAULT_PASSWORD.getBytes(encoding);
                byte[] ipBytes = DEFAULT_IP.getBytes(encoding);
                
                System.arraycopy(usernameBytes, 0, stDevLoginInfo.szUserName, 0, usernameBytes.length);
                System.arraycopy(passwordBytes, 0, stDevLoginInfo.szPassword, 0, passwordBytes.length);
                System.arraycopy(ipBytes, 0, stDevLoginInfo.szIPAddr, 0, ipBytes.length);
                
                stDevLoginInfo.dwPort = Integer.parseInt(DEFAULT_PORT);
                stDevLoginInfo.dwLoginProto = 1;
                
                NetDemo.lpUserID = NetDemo.netdevsdk.NETDEV_Login_V30(stDevLoginInfo, stSELogInfo);
                
                if (NetDemo.lpUserID != null) {
                    System.out.println("✅ 编码 " + encoding + " 登录成功!");
                    autoLogout();
                    return;
                } else {
                    int errorCode = NetDemo.netdevsdk.NETDEV_GetLastError();
                    System.out.println("❌ 编码 " + encoding + " 失败，错误代码: " + errorCode);
                }
            } catch (Exception e) {
                System.err.println("测试编码 " + encoding + " 异常: " + e.getMessage());
            }
        }
    }
    
    /**
     * 自动登出
     */
    public static void autoLogout() {
        if (NetDemo.lpUserID != null) {
            System.out.println("执行登出...");
            NetDemo.netdevsdk.NETDEV_Logout(NetDemo.lpUserID);
            NetDemo.lpUserID = null;
            System.out.println("登出完成");
        }
    }

    public static void allLogin(){
        // 步骤1: 测试SDK初始化
        testSDKInitialization();

        // 步骤2: 完全复制UI登录逻辑
        autoLogin();
    }

    public static void main(String[] args) {
        // 步骤1: 测试SDK初始化
        testSDKInitialization();
        
        // 步骤2: 完全复制UI登录逻辑
        autoLogin();
        
        // 步骤3: 如果失败，测试不同编码
//        if (NetDemo.lpUserID == null) {
//            testDifferentEncodings();
//        }
    }
}